﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using UTSDAL.LINQSQL.Model;
using UTSDAL.LINQSQL.Helper;

namespace UTSDAL.SQL
{
    /// <summary>
    /// Connection manager which performs normal db operations
    /// </summary>
    public class ConnectionManager
    {
        /// <summary>
        /// private constructor will forces the singleton pattern
        /// </summary>
        private ConnectionManager()
        {

        }

        // the connection manager instance which is provided to calling instances
        private static ConnectionManager instance = null;

        /// <summary>
        /// retrieves a single instance of the connection manager class through the singleton pattern
        /// </summary>
        /// <returns>a unique and synchronized instance of the connection manager class</returns>
        public static ConnectionManager getInstance()
        {
            if (instance == null)
            {
                instance = new ConnectionManager();
            }

            return instance;
        }
        
       
        /// <summary>
        /// the SQLConnection object to be used for read and write operations to and from the database
        /// </summary>
        private SqlConnection connection = null;

        /// <summary>
        /// the SQLConnection object to be used for read and write operations to and from the database
        /// </summary>
        public SqlConnection Connection
        {
            get 
            {
                if (connection == null)
                {
                    String connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["UTSDAL.Properties.Settings.UTSDBConnectionString"].ConnectionString;

                    connection = new SqlConnection(connectionString);
                }

                UTSDataContext context = DataContextHelper.Context;
                

                return connection; 
            }
            set { connection = value; }
        }



        public void update(String query, List<SqlParameter> parameters)
        {
            
            SqlCommand command = new SqlCommand(query,this.Connection);

            if (parameters != null)
            {
                foreach (SqlParameter parameter in parameters)
                {
                    command.Parameters.Add(parameter);
                }
            }

            try
            {
                this.Connection.Open();
                command.ExecuteNonQuery();
            }
            finally
            {
                this.Connection.Close();
            }
        }
            
    }
}
